﻿using System;
using System.Collections.Generic;
using Core.Domain;

namespace Core.SyntaxAnalysis.Classes
{
    public class REPEAT : Stmt
    {
        private readonly Expr m_condition;
        private readonly Stmt m_body;

        public REPEAT(Expr condition, Stmt body)
        {
            m_condition = condition;
            m_body = body;
        }

        public override bool StmtSemanticCheck(ref List<CompilerError> errors)
        {
            var error = false;
            try
            {
                var t = m_condition.GetExprType();
                if (!(t is Boolean))
                {
                    error = true;
                    errors.Add(new CompilerError(errors.Count + 1, Resources.SyntaxErrorConditionTypeShouldBeBoolean, m_condition.GetLexem()));
                }
            }
            catch (Exception ex)
            {
                error = true;
                errors.Add(new CompilerError(errors.Count + 1, ex.Message, -1, -1));
            }
            if (m_body!= null && !m_body.SemanticCheck(ref errors))
            {
                error = true;
            }
            return !error;
        }


        public override void StmtGenerate(System.Text.StringBuilder s)
        {
            var lblStart = Env.NextLabel();
            CodeGenerator.AppendLabel(s, lblStart);
            m_body.Generate(s);
            var exprID = m_condition.Generate(s);
            CodeGenerator.AppendIfNotGoto(s, exprID, lblStart);
        }
    }
}